<?php

namespace addons\vppz\controller;

use app\admin\model\vppz\Qxzl;
use app\admin\model\vppz\User;
use app\common\library\token\driver\Redis;
use think\Db;
use think\addons\Controller;

use addons\epay\library\Service as PayService;
//use fast\Random;
use Exception;

use EasyWeChat\Factory as EasyWeChatFactory;


use \app\admin\model\vppz\App as AppModel;
use \app\admin\model\vppz\Order as OrderModel;
use \app\admin\model\vppz\Qxzl as QxzlModel;
use \app\admin\model\vppz\Area as AreaModel;
use \app\admin\model\vppz\Staff as StaffModel;

use \app\admin\model\vppz\ServiceOrder as ServiceOrderModel;
use \app\admin\model\vppz\VipOrder as VipOrderModel;
use \app\admin\model\vppz\User as UserModel;
use \app\admin\model\vppz\VipPackage as VipPackageModel;
use \app\admin\model\vppz\OrderServiceDetail as OrderServiceDetailModel;
use \app\admin\model\vppz\ExaminationOrder as ExaminationOrderModel;

class Pay extends Controller
{
	/**
	public function _initialize(){
        parent::_initialize();

		// 运营区域
		$this->OrderModel = new OrderModel;
    }
	**/

	// 支付回调 TODO:日志
    public function notify(){
		\think\Log::write('[vppz][pay]支付回调');
        $postStr = file_get_contents("php://input");
        file_put_contents('/www/wwwroot/peizhen.banyetang.cn/public/'.date('Y-m-d').'_order.txt',$postStr."\n", FILE_APPEND);
        $paytype = $this->request->param('paytype');	// wechat:微信，alipay:支付宝
        $pay = PayService::checkNotify($paytype);
        if (!$pay) {
			\think\Log::write('[vppz][pay:error]交易失败，签名错误');
            //echo '签名错误';
            return;
        }
        $data = $pay->verify();
        $data = \Tools::xmlToArray($postStr);
		\think\Log::write($data);
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
			$data['fee']= $payamount;	// 在支付反馈数据中增加支付总额（单位：元）

            $out_trade_no = $data['out_trade_no'];
			 //你可以在此编写订单逻辑
			// 判定订单类型，交于相应后续业务逻辑处理
			$tinfo=explode('_',$out_trade_no);
			if(count($tinfo)!=2){
				//echo '交易失败，订单号错误';
				\think\Log::write('[vppz][pay:error]交易失败，订单号错误：'.$out_trade_no);
				\think\Log::write($data);
				return;
			}
			$data['order_id']=$tinfo[1];	// 在支付反馈数据中增加当前业务的订单ID

			// 根据订单业务处理订单
			if($tinfo[0]=='SEV'){
				//\think\Log::write('[vppz][pay]服务类订单处理');
				//\think\Log::write($data);
				$this->payResultSEV($data);
			}elseif($tinfo[0]=='QXZL'){
				//\think\Log::write('[vppz][pay]器械租赁');
				//\think\Log::write($data);
				$this->payResultQXZL($data);
			}elseif($tinfo[0]=='KANGYANG'){
				$this->payResultKANGYANG($data);
			}elseif($tinfo[0]=='VIP'){
				$this->payResultVIP($data);
			}elseif($tinfo[0] == 'tijian'){
                $this->payResultTIJIAN($data);
            }else{
				//echo '交易失败，订单业务不存在';
				\think\Log::write('[vppz][pay:error]交易失败，订单业务不存在：'.$out_trade_no);
				\think\Log::write($data);
				return;
			}

			/*** 测试

			$OrderModel = new OrderModel;
			$OrderModel->save([
				'pay_params'  => serialize($data)
			],['id' => 1]);
			**/

        } catch (Exception $e) {
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }
    //康养套餐
    public function kangyangnotify(){
		\think\Log::write('[vppz][pay]支付回调');
        $paytype = $this->request->param('paytype');	// wechat:微信，alipay:支付宝
        $pay = PayService::checkNotify($paytype);
        if (!$pay) {
			\think\Log::write('[vppz][pay:error]交易失败，签名错误');
            //echo '签名错误';
            return;
        }
        $data = $pay->verify();
		\think\Log::write($data);
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
			$data['fee']= $payamount;	// 在支付反馈数据中增加支付总额（单位：元）

            $out_trade_no = $data['out_trade_no'];
			 //你可以在此编写订单逻辑
			// 判定订单类型，交于相应后续业务逻辑处理
			$tinfo=explode('_',$out_trade_no);
			if(count($tinfo)!=2){
				//echo '交易失败，订单号错误';
				\think\Log::write('[vppz][pay:error]交易失败，订单号错误：'.$out_trade_no);
				\think\Log::write($data);
				return;
			}
			$data['order_id']=$tinfo[1];	// 在支付反馈数据中增加当前业务的订单ID

			// 根据订单业务处理订单
			if($tinfo[0]=='SEV'){
				//\think\Log::write('[vppz][pay]服务类订单处理');
				//\think\Log::write($data);
				$this->payResultSEV($data);
			}elseif($tinfo[0]=='QXZL'){
				//\think\Log::write('[vppz][pay]器械租赁');
				//\think\Log::write($data);
				$this->payResultQXZL($data);
			}else{
				//echo '交易失败，订单业务不存在';
				\think\Log::write('[vppz][pay:error]交易失败，订单业务不存在：'.$out_trade_no);
				\think\Log::write($data);
				return;
			}

			/*** 测试

			$OrderModel = new OrderModel;
			$OrderModel->save([
				'pay_params'  => serialize($data)
			],['id' => 1]);
			**/

        } catch (Exception $e) {
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }


	// 服务类交易回调业务处理
	protected function payResultSEV($params){
		$OrderModel = new OrderModel;

		$order = $OrderModel->find($params['order_id']);

		// 订单及金额验证
		if(empty($order)){
			//echo '交易失败，订单不存在';
			\think\Log::write('[vppz][pay:error]交易失败，订单不存在：'.$params['order_id']);
			\think\Log::write($params);
			return;
		}
		/**
		if(intval($order['to_pay']*100)<1 || round($order['to_pay']*100)!=round(floatval($params['fee'])*100)){
			echo '交易失败，订单金额不符';
			return;
		}
		**/



		// 更新订单付款状态
		$orderUp=[
			'status'=>20,
			'status_time'=>time(),
			'pay'=>$params['fee'],
			'pay_params'=>serialize($params),
			'pay_time'=>time()
		];
		$ret = $OrderModel->save($orderUp,['id' =>$order['id']]);

		if(!($ret>0)){
			\think\Log::write('[vppz][pay:error]交易失败，订单更新失败');
			\think\Log::write($orderUp);
			return;
		}

		// 更新用户下单数
		Db::name('vppz_user')->where(['app_id'=>$order['app_id'],'id'=>$order['user_id']])->inc('orders',1)->update();

		//pdo_query('UPDATE '.tablename('vp_pz_order') .' SET status=20,status_time=:status_time,pay=:pay,pay_params=:pay_params,pay_time=:pay_time where id=:id', array(':id' => $order['id'],':pay' =>  $params['fee'],':pay_params' => iserializer($params),':status_time' => time(),':pay_time' => time()));
        $userInfo = Db::name('vppz_user')->where(['app_id'=>$order['app_id'],'id'=>$order['user_id']])->find();
        if(empty($userInfo) === FALSE){
            $redis = new Redis();
            $key = "bangyetang_qipao_info";

            $redis->lpush($key,json_encode(array(
                'user'=>$userInfo->nickname,
                'action'=>'购买了服务'
            )));
        }

		/*** TODO **/
		// 通知相应人员接单
		$AppModel = new AppModel;
		$cfg = $AppModel->find($order['app_id']);

		if(!empty($cfg['nt_order_new'])){
			$AreaModel = new AreaModel;
			$StaffModel = new StaffModel;

			// 判断模式，如果是抢单模式，通知所有同城陪护师(TODO 后期优化为陪护师订阅某些医院的通知)；如果是派单模式，通知所有同城派单员
			$area = $AreaModel->where(['app_id'=>$order['app_id'],'id'=>$order['area_id']])->find();

			//$openids=array();
			$keyword3='';
			$remark='';
			$staffs=array();

			if($order['staff_toid']>0){
				// 已选择服务专员
				$keyword3 = '等待服务';
				$remark = '点击前往查看处理';
				//$staffs = pdo_fetchall('SELECT openid FROM ' .tablename('vp_pz_staff') . ' where uniacid=:uniacid AND city_id=:city_id AND status=20 AND is_dis=0 ', array(':uniacid' => $_W['uniacid'],':city_id'=>$order['city_id']));
				$staffs = $StaffModel->field('openid,acopenid')->where(['app_id'=>$order['app_id'],'id'=>$order['staff_toid'],'status'=>20,'stop_switch'=>0])->select();
			}else{
				// 未选择服务专员
				if($area['odmode']==0){
					$keyword3 = '等待接单';
					$remark = '点击前往查看接单';
					//$staffs = pdo_fetchall('SELECT openid FROM ' .tablename('vp_pz_staff') . ' where uniacid=:uniacid AND city_id=:city_id AND status=20 AND is_dis=0 ', array(':uniacid' => $_W['uniacid'],':city_id'=>$order['city_id']));
					$staffs = $StaffModel->field('openid,acopenid')->where(['app_id'=>$order['app_id'],'area_id'=>$area['id'],'status'=>20,'stop_switch'=>0])->select();
				}else if($area['odmode']==10){
					$keyword3 = '等待派单';
					$remark = '点击前往查看派单';
					//$staffs = pdo_fetchall('SELECT openid FROM ' .tablename('vp_pz_staff') . ' where uniacid=:uniacid AND city_id=:city_id AND odmanar=10 AND status=20 AND is_dis=0 ', array(':uniacid' => $_W['uniacid'],':city_id'=>$order['city_id']));
					$staffs = $StaffModel->field('openid,acopenid')->where(['app_id'=>$order['app_id'],'area_id'=>$area['id'],'status'=>20,'stop_switch'=>0,'odmanar'=>1])->select();
				}
			}

			$pdata = array(
				'first' => array(
					'value' => '有新的服务订单',
					'color' => '#f73959'
				),
				'keyword1' => array(
					'value' => $order['area_name']
				),
				'keyword2' => array(
					'value' => $order['title']
				),
				'keyword3' => array(
					'value' => $keyword3
				),
				'remark' => array(
					'value' => $remark
				)
			);

			// 新-公众号模板消息
			$acc = EasyWeChatFactory::officialAccount(['app_id' => $cfg['mpappid'],'secret' => $cfg['mpappsecret']]);
			for($i=0;$i<count($staffs);$i++){
				if($staffs[$i]['acopenid']){
					$ret = $acc->template_message->send([
						'touser' => $staffs[$i]['acopenid'],
						'template_id' => $cfg['nt_order_new'],
						'miniprogram' => [
								'appid' => $cfg['wxapp_id'],
								'pagepath' => 'vp_pz/pages/staff/index',
						],
						'data' => $pdata
					]);
				}
			}

			/** 原-统一模板消息
			$WxappApi = EasyWeChatFactory::miniProgram([
				'app_id'    => $cfg['wxapp_id'],
				'secret'    => $cfg['wxapp_secret']
			]);
			for($i=0;$i<count($staffs);$i++){
				$ret = $WxappApi->uniform_message->send([
					'touser' => $staffs[$i]['openid'],
					'mp_template_msg'=>[
						'appid'=>$cfg['mpappid'],
						'template_id'=>$cfg['nt_order_new'],
						'miniprogram'=>array(
							'appid'=>$cfg['wxapp_id'],
							'pagepath'=>'vp_pz/pages/staff/index',
						),
						'data'=>$pdata
					]
				]);
			}
			**/
		}

	}
    //器械租赁
	protected function payResultQXZL($params){
		$OrderModel = new OrderModel;

		$order = $OrderModel->find($params['order_id']);

        $content = '';
		// 订单及金额验证
		if(empty($order)){
			//echo '交易失败，订单不存在';
			\think\Log::write('[vppz][pay:error]交易失败，订单不存在：'.$params['order_id']);
			\think\Log::write($params);
			return;
		}
		/**
		if(intval($order['to_pay']*100)<1 || round($order['to_pay']*100)!=round(floatval($params['fee'])*100)){
			echo '交易失败，订单金额不符';
			return;
		}
		**/
        $user = User::get($order['user_id']);
        $qixie = Qxzl::get($order['equipment_id']);
        if($order['saletype'] == 'rent'){
            $content = '用户:'.$user['nickname'].'租赁设备:'.$qixie['name'].'请及时关注';
            $contentinfo = '租赁设备:'.$qixie['name'];
        }else{
            $content = '用户:'.$user['nickname'].'采购设备:'.$qixie['name'].'请及时关注';
            $contentinfo = '采购设备:'.$qixie['name'];
        }


        $OrderModel->startTrans();
        $opera = [];
		// 更新订单付款状态
		$orderUp=[
			'status'=>20,
			'status_time'=>time(),
			'pay'=>$params['fee'],
			'pay_params'=>serialize($params),
			'pay_time'=>time()
		];
		$opera[] = $OrderModel->save($orderUp,['id' =>$order['id']]);

		if(!\Tools::checkArrayResult($opera)){
			\think\Log::write('[vppz][pay:error]交易失败，订单更新失败');
			\think\Log::write($orderUp);
            $OrderModel->rollback();
			return;
		}

		//更新库存
        $QxzlModel = new QxzlModel();
        $opera[] = $QxzlModel->where('id',$order['service_id'])->setDec('stock');
        if(!\Tools::checkArrayResult($opera)){
			\think\Log::write('[vppz][pay:error]交易失败，更新库存失败');
			\think\Log::write($orderUp);
            $OrderModel->rollback();
			return;
		}
        hook('send_message', [1, 'system', '器械租售', $content]);
        $redis = new Redis();
        $key = 'system_msg_key';
        $redis->lpush($key,1);
        hook('send_message', [$order['user_id'], 'user', '器械租售', $content]);

        \TempNotice::qixiezushoutoadmin($content);

        $qipaokey = "bangyetang_qipao_info";

        $redis->lpush($qipaokey,json_encode(array(
            'user'=>$user['nickname'],
            'action'=>$contentinfo
        )));
        $OrderModel->commit();
	}
    //康养
	protected function payResultKANGYANG($params){
		$OrderModel = new ServiceOrderModel;

		$order = $OrderModel->find($params['order_id']);

		// 订单及金额验证
		if(empty($order)){
			//echo '交易失败，订单不存在';
			\think\Log::write('[vppz][pay:error]交易失败，订单不存在：'.$params['order_id']);
			\think\Log::write($params);
			return;
		}
        $content = '客户：'.$order['customer_name'].'下单康养套餐：'.$order['package_name'].',支付：'.$order['actual_amount'];


		/**
		if(intval($order['to_pay']*100)<1 || round($order['to_pay']*100)!=round(floatval($params['fee'])*100)){
			echo '交易失败，订单金额不符';
			return;
		}
		**/

        $OrderModel->startTrans();
        $opera = [];
		// 更新订单付款状态
		$orderUp=[
			'order_status'=>1,
			'pay_params'=>serialize($params),
			'pay_time'=>time()
		];
		$opera[] = $OrderModel->save($orderUp,['order_id' =>$order['order_id']]);
        $detaildata = [
            'expiretime'=>strtotime("+".$order['length']." months", time()),
            'updatetime'=>time()
        ];
        $OrderdetailModel = new OrderServiceDetailModel;
        $detail = $OrderdetailModel->where([
            'order_id'=>$order['id']
        ])->find();
        if(empty($detail) === FALSE) {
            $opera[] = $OrderdetailModel->where([
                'order_id' => $order['id']
            ])->update($detaildata);
        }
		if(!\Tools::checkArrayResult($opera)){
			\think\Log::write('[vppz][pay:error]交易失败，订单更新失败');
			\think\Log::write($orderUp);
            $OrderModel->rollback();
			return;
		}

        hook('send_message', [1, 'system', '康养套餐', $content]);
        $redis = new Redis();
        $key = 'system_msg_key';
        $redis->lpush($key,1);
        hook('send_message', [$order['user_id'], 'user', '康养套餐', $content]);
        $content = '客户购买康养套餐:'.$order['package_name'].',请及时关注';
        \TempNotice::kangyangtoadmin($content);

        $qipaokey = "bangyetang_qipao_info";

        $redis->lpush($qipaokey,json_encode(array(
            'user'=>$order['customer_name'],
            'action'=>'下单康养套餐'
        )));
        $OrderModel->commit();
	}
    protected function payResultVIP($params){
		$OrderModel = new VipOrderModel;
		$VipPackageModel = new VipPackageModel();

		$order = $OrderModel->find($params['order_id']);

		// 订单及金额验证
		if(empty($order)){
			//echo '交易失败，订单不存在';
			\think\Log::write('[vppz][pay:error]交易失败，订单不存在：'.$params['order_id']);
			\think\Log::write($params);
			return;
		}
        $OrderModel->startTrans();
        $opera = [];
		// 更新订单付款状态
		$orderUp=[
			'order_status'=>1,
			'pay_params'=>serialize($params),
			'pay_time'=>time()
		];
		$opera[] = $OrderModel->save($orderUp,['id' =>$order['id']]);
        $package = $VipPackageModel->where(['id'=>$order['package_id']])->find();
        //更新会员状态
        $detaildata = [
            'vip_time'=>datetime(time(),'Y-m-d H:i:s'),
            'is_vip'=>1,
            'expire_time'=>datetime(strtotime("+".$package['duration']." months", time()),'Y-m-d H:i:s'),
            'updatetime'=>time(),
            'content'=>$package['content']
        ];
        $userModel = new UserModel();
        $user = $userModel->where(['id'=>$order['user_id']])->find();

        $content = '用户：'.$user['nickname'].'开通家庭医生会员,请提供服务';
        $opera[] = $userModel->where(['id'=>$order['user_id']])->update($detaildata);
		if(!\Tools::checkArrayResult($opera)){
			\think\Log::write('[vppz][pay:error]交易失败，订单更新失败');
			\think\Log::write($orderUp);
            $OrderModel->rollback();
			return;
		}
        hook('send_message', [1, 'system', '家庭医生会员', $content]);
        $redis = new Redis();
        $key = 'system_msg_key';

        $redis->lpush($key,1);
        hook('send_message', [$order['user_id'], 'user', '家庭医生会员', $content]);
        \TempNotice::familyviptoadmin($content);

        $keytip = "bangyetang_qipao_info";

        $redis->lpush($keytip,json_encode(array(
            'user'=>$user['nickname'],
            'action'=>'开通家庭医生会员'
        )));
        $OrderModel->commit();
	}
    //体检
	protected function payResultTIJIAN($params){
		$OrderModel = new ExaminationOrderModel;

		$order = $OrderModel->find($params['order_id']);

		// 订单及金额验证
		if(empty($order)){
			//echo '交易失败，订单不存在';
			\think\Log::write('[vppz][pay:error]交易失败，订单不存在：'.$params['order_id']);
			\think\Log::write($params);
			return;
		}
		// 更新订单付款状态
		$orderUp=[
			'status'=>1,
			'pay_time'=>time(),
			'pay_params'=>serialize($params)
		];
		$ret = $OrderModel->save($orderUp,['id' =>$order['id']]);

		if(!($ret>0)){
			\think\Log::write('[vppz][pay:error]交易失败，订单更新失败');
			\think\Log::write($orderUp);
			return;
		}
        $userInfo = Db::name('vppz_user')->where(['app_id'=>$order['app_id'],'id'=>$order['user_id']])->find();
        if(empty($userInfo) === FALSE){
            $redis = new Redis();
            $key = "bangyetang_qipao_info";

            $redis->lpush($key,json_encode(array(
                'user'=>$userInfo->nickname,
                'action'=>'购买了体检套餐'
            )));
        }

        $content = '用户:'.$userInfo->nickname.'购买了体检套餐';
        hook('send_message', [1, 'system', '体检套餐', $content]);
        $redis = new Redis();
        $key = 'system_msg_key';

        $redis->lpush($key,1);
        hook('send_message', [$order['user_id'], 'user', '体检套餐', $content]);
        \TempNotice::tijiantoadmin($content);
	}
}
